<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;


class Base extends Controller
{
	public function _initialize()
    {
        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        $res =  preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';        
        $request = Request::instance();
        $url='http://ip.taobao.com/service/getIpInfo.php?ip='.$res;
        $result = file_get_contents($url);
        // $result = json_decode($result,true); //二维数组
        $result = json_decode($result,true)['data'];//一维数组
        $result['ip'] = '112.112.113.112';
        $userip = db('userip')->where('ip',$result['ip'])->find();
        $today = strtotime(date('Y-m-d'));//一天中的零时零分零秒
        if ($result['ip'] == $userip['ip']) {
            if ($userip['time'] < $today) {
                $result['time'] = time();
                db('userip')->where('ip',$userip['ip'])->update($result);
            }
        }else {
            $result['time'] = time();
            db('userip')->insert($result);
        }


        //导航 nav
        $nav=db('cate')->where('show',1)->order('sort')->select();
        
        $this->assign('_nav',$nav);
        //主体信息 SEO
        if (!cache('seo_info')) {
            $seo=db('basic')->where('id',1)->find();
            cache('seo_info',$seo,3600);
        }
        $this->assign('_seo',cache('seo_info'));
        // 最新动态 postion_new
        $postion_new = db('article')->order('id desc')->limit(6)->select();
        $this->assign('postion_new',$postion_new);
        // 统计文章数量 article_count
        $article_count=db('article')->count();
        $this->assign('article_count',$article_count);
        // banner图片
        $banner=db('banner')->where('show',1)->order('sort')->select();
        $this->assign('banner',$banner);
        
        // 标签云
        $tagdata=db('article')->field('tag')->select();
        $this->assign('tag',$this->taglist($tagdata));
    }

    public function taglist($data)
    {
        $arr = array();
        $tagarr = array();
        foreach ($data as $k => $v) {
            $arr=explode(',',strtoupper($v['tag']));//转换为大写
            for ($i=0; $i <count($arr) ; $i++) { 
                $tagarr[] = $arr[$i];
            }
        }
        cache('tagcache',array_keys(array_flip($tagarr)+array_flip($tagarr)),3600);
        return array_keys(array_flip($tagarr)+array_flip($tagarr));
    }

}
